﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Base.Common;

namespace BaseApplication.Controllers
{
    public class HomeController : BaseController
    {
        public virtual ActionResult Index()
        {
            ViewBag.Message = "Welcome to ASP.NET MVC!";

            return View();
        }

        public ActionResult About()
        {
            return View();
        }

        /// <summary>
        /// change language
        /// </summary>
        /// <param name="lang"></param>
        /// <returns></returns>
        public ActionResult ChangeLanguage(string Language)
        {
            /*记录语言设置到cookies*/
            HttpCookie cookie = new HttpCookie("Language", Language);
            this.CurrentLanguage = Language;
            //指定客户端脚本是否可以访问[默认为false]
            cookie.HttpOnly = false;
            //指定统一的Path，比便能通存通取
            cookie.Path = "/";
            //设置跨域,这样在其它二级域名下就都可以访问到了
            //cookie.Domain = "chinesecoo.com";
            //有效期
            cookie.Expires = DateTime.Now.AddDays(30);
            Response.AppendCookie(cookie);
            /*重定向到上一个Action*/
            string url = this.Request.ServerVariables["HTTP_REFERER"];
            //if (CurrentLanguage.Equals(Constant.Language.zh_CN))
            //{
            //    return new RedirectResult(this.Request.ServerVariables["HTTP_REFERER"]);
            //}
            //else
            //{
            //    return new RedirectResult(this.Request.ServerVariables["HTTP_REFERER"]);
            //    //   return new RedirectResult(CurrentLanguage.Replace("-", "_") + Request.Url.LocalPath);
            //}
            // return RedirectToAction("Index");
            //return View("Index");

            return new RedirectResult(GetURL(CurrentLanguage, this.Request.ServerVariables["HTTP_REFERER"]));
        }

        private string GetURL(string Language, string url)
        {
            //en_US
            url = url.Replace(Constant.Language.en_US.Replace("-", "_") + "/", "");
            url = url.Replace(Constant.Language.en_US.Replace("-", "_"), "");

            if (CurrentLanguage.Equals(Constant.Language.zh_CN))
                return url;
            else
            {
                int start = url.IndexOf("/", 7);
                string newURL = url.Substring(0, start) + "/" + Constant.Language.en_US.Replace("-", "_") + url.Substring(start, url.Length - start);
                return newURL;
            }

        }
    }
}
